package com.yanqu.road.web.controller.usercenter.newadmin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.servercenter.ServerAutoOpenConfigDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.entity.servercenter.ServerAutoOpenConfig;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.server.manger.AutoOpenServerMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.mgr.RegisterPlayerNumMgr;
import com.yanqu.road.web.mgr.RoleCreateCountMgr;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@RestController
public class CenterAutoOpenServerController {

    private static Logger logger = LogManager.getLogger(CenterAutoOpenServerController.class.getName());
    /**
     *  47.1 指定时间段内开服的区服信息（已经设置了开服状态和开服时间的区服）
     */
    @ResponseBody
    @RequestMapping(value = "getOpenServer", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getOpenServer(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("channelId") || !jsonObject.containsKey("startTime")){
            return AdminResult2.failCode(1, "参数不足").toJsonString();
        }

        int channelId = jsonObject.getIntValue("channelId");
        long startTime = jsonObject.getLongValue("startTime") / 1000;
        long endTime = 0;
        if(jsonObject.containsKey("endTime")){
            endTime = jsonObject.getLongValue("endTime") / 1000;
        }
        AdminResult2 result2 = new AdminResult2();
        List<ServerInfo> channelServerList = ServerListMgr.getChannelServerList(channelId);
        for (ServerInfo serverInfo : channelServerList) {
            if(!serverInfo.isOpen()){
                continue;
            }
            if(serverInfo.getOpenTime() < startTime){
                continue;
            }
            if(endTime > 0 && serverInfo.getOpenTime() > endTime){
                continue;
            }
            Map<String, Object> objMap = new HashMap<>();
            objMap.put("serverId", serverInfo.getServerId());
            objMap.put("openTime", serverInfo.getOpenTime() * 1000);
            objMap.put("splitFlow", serverInfo.isOpenSplitFlow() ? 1 : 0);
            result2.getData().add(objMap);
        }
        return result2.toJsonString();
    }

    /**
     *  47.2 获取待开区服信息（未设置开服状态和时间，但已准备就绪可以投入使用的区服）
     */
    @ResponseBody
    @RequestMapping(value = "getReadyServer", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getReadyServer(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("channelId")){
            return AdminResult2.failCode(1, "参数不足").toJsonString();
        }

        int channelId = jsonObject.getIntValue("channelId");

        AdminResult2 result2 = new AdminResult2();
        List<ServerInfo> channelServerList = ServerListMgr.getChannelServerList(channelId);
        for (ServerInfo serverInfo : channelServerList) {
            if(serverInfo.isOpen()){
                continue;
            }
            if(serverInfo.getState() == 0){
                continue;
            }
            Map<String, Object> objMap = new HashMap<>();
            objMap.put("serverId", serverInfo.getServerId());
            objMap.put("serverName", serverInfo.getServerName());
            objMap.put("labelName", serverInfo.getMarkStr());
            result2.getData().add(objMap);
        }
        return result2.toJsonString();
    }

    /**
     *  47.3 获取当前导量的区服（实际在导量的/没导量，但导量开关开启）
     */
    @ResponseBody
    @RequestMapping(value = "getSplitFlowServer", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getSplitFlowServer(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("channelId") || !jsonObject.containsKey("type")){
            return AdminResult2.failCode(1, "参数不足").toJsonString();
        }

        int channelId = jsonObject.getIntValue("channelId");

        int type = 1; //1 创角  2 有效创角   3 注册人数  4 充值人数

        if(jsonObject.containsKey("type")){
            type = jsonObject.getIntValue("type");
        }

        AdminResult2 result2 = AdminResult2.defaultInstance();

        List<ServerInfo> serverList = ServerListMgr.getSplitFlowServerList();
        for (ServerInfo serverInfo : serverList) {
            if(channelId > 0 && serverInfo.getChannelId() != channelId){
                continue;
            }
            //注册人数
            int registerNum = RegisterPlayerNumMgr.getRegisterNumByServerId(serverInfo.getServerId());

            String serverData = "";
            JSONObject dataObj;
            try {
                serverData = HttpHelper.doPostJsonTimeOut(serverInfo.getWebServerUrl() + "/queryServerRoleCreate", jsonObject.toJSONString(), "UTF-8", new HashMap<>());
                JSONObject jsonObj = JSONObject.parseObject(serverData);
                if(null != jsonObj) {
                    dataObj = jsonObj.getJSONObject("" + serverInfo.getServerId());
                    if (null == dataObj) {
                        if(jsonObj.containsKey("state")){
                            logger.error("state code : {}", jsonObj.get("state"));
                            //直接返回缓存数据
                            dataObj = new JSONObject();
                            if(type == 1){
                                dataObj.put("role", RoleCreateCountMgr.getRoleCreateCountByServerId(serverInfo.getServerId()));
                            }else if(type == 2){
                                dataObj.put("role", RoleCreateCountMgr.getValidCreateCountByServerId(serverInfo.getServerId()));
                            }else if(type == 3){
                                dataObj.put("role", RegisterPlayerNumMgr.getRegisterNumByServerId(serverInfo.getServerId()));
                            }
                            dataObj.put("limit", serverInfo.getCreateRoleCountLimit());
                        }
                    }

                    if(dataObj != null) {
                        dataObj.put("serverId", serverInfo.getServerId());
                        dataObj.put("regNum", registerNum);
                        if(dataObj.containsKey("role")){
                            dataObj.put("num", dataObj.get("role"));
                            int num = dataObj.getIntValue("num");
                            if(type == 1){
                                int actualSplitFlow = num >= serverInfo.getCreateRoleCountLimit() ? 2 : 1;
                                dataObj.put("actualSplitFlow", actualSplitFlow);
                            }else if(type == 2){
                                int actualSplitFlow = num >= serverInfo.getCreateRoleCountLimit() ? 2 : 1;
                                dataObj.put("actualSplitFlow", actualSplitFlow);
                            }else if(type == 3){
                                int actualSplitFlow = num >= serverInfo.getCreateRoleCountLimit() ? 2 : 1;
                                dataObj.put("actualSplitFlow", actualSplitFlow);
                            }
                        }
                        result2.getData().add(dataObj);
                    }
                }
            } catch (Exception ex) {
                logger.error("json parse error,{},error:", serverData, ex);
            }
        }
        return result2.toJsonString();
    }


    /**
     *  47.4  获取指定时段指定区服每小时的（创角/有效创角/注册人数/付费人数）
     */
    @ResponseBody
    @RequestMapping(value = "serverNumEveryHour", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String serverNumEveryHour(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("serverList")){
            return AdminResult2.failCode(1, "参数不足").toJsonString();
        }

        JSONArray serverList = jsonObject.getJSONArray("serverList");

        AdminResult2 result2 = new AdminResult2();

        for (int i = 0; i < serverList.size(); i++) {
            long serverId = serverList.getLongValue(i);
            ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
            if (serverInfo == null) {
                continue;
            }
            String serverData = "";
            try {
                serverData = HttpHelper.doPostJsonTimeOut(serverInfo.getWebServerUrl() + "/queryTimeServerRoleCreate2", jsonObject.toJSONString(), "UTF-8", new HashMap<>());
                JSONObject jsonObj = JSONObject.parseObject(serverData);
                if(null != jsonObj) {
                    JSONObject dataObj = jsonObj.getJSONObject("" + serverId);
                    if (null != dataObj) {
                        dataObj.put("serverId", serverId);
                        dataObj.put("openTime", serverInfo.getOpenTime() * 1000);
                        result2.getData().add(dataObj);
                    }
                }
            } catch (Exception ex) {
                logger.error("json parse error,{},error:", serverData, ex);
            }
        }
        return result2.toJsonString();
    }


    /**
     *  47.5 获取当前在线人数的接口
     */
    @ResponseBody
    @RequestMapping(value = "serverOnline", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String serverOnline(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("serverList")){
            return AdminResult2.failCode(1, "参数不足").toJsonString();
        }

        AdminResult2 result2 = new AdminResult2();

        JSONArray serverList = jsonObject.getJSONArray("serverList");

        for (int i = 0; i < serverList.size(); i++) {
            long serverId = serverList.getLongValue(i);
            ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
            if (serverInfo == null) {
                continue;
            }
            String serverData = "";
            try {
                serverData = HttpHelper.doPostJsonTimeOut(serverInfo.getWebServerUrl() + "/queryServerOnline", jsonObject.toJSONString(), "UTF-8", new HashMap<>());
                JSONObject jsonObj = JSONObject.parseObject(serverData);
                if(null != jsonObj) {
                    JSONObject dataObj = jsonObj.getJSONObject("" + serverId);
                    if (null != dataObj) {
                        dataObj.put("serverId", serverId);
                        result2.getData().add(dataObj);
                    }
                }
            } catch (Exception ex) {
                logger.error("json parse error,{},error:", serverData, ex);
            }
        }

        return result2.toJsonString();
    }

    /**
     *  47.6  导量判断标准通知(旧接口-已有)
     */
//    @ResponseBody
//    @RequestMapping(value = "consoleServerRoleType", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
//    public String consoleServerRoleType(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
//
//        if(!jsonObject.containsKey("channelId") || !jsonObject.containsKey("type")){
//            return AdminResult2.failCode(1, "参数不足").toJsonString();
//        }
//
//        int channelId = jsonObject.getIntValue("channelId");
//        int type = jsonObject.getIntValue("type");
//
//        int areaType = 1;
//        if(jsonObject.containsKey("areaType")){
//            areaType = jsonObject.getIntValue("areaType");
//        }
//        String areaSplitFlow = "";
//
//        if(jsonObject.containsKey("areaSplitFlow")){
//            areaSplitFlow = jsonObject.getString("areaSplitFlow");
//        }else {
//            ServerAutoOpenConfig config = AutoOpenServerMgr.getAutoOpenConfigMap().get(type);
//            if (config != null) {
//                areaSplitFlow = config.getAreaSplitFlow();
//            }
//        }
//
//
//        return AdminResult.defaultInstance().toJsonString();
//    }

    /**
     *  47.7  获取指定区服总的
     */
    @ResponseBody
    @RequestMapping(value = "serverNumTotal", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String serverNumTotal(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("serverList") || !jsonObject.containsKey("type")){
            return AdminResult2.failCode(1, "参数不足").toJsonString();
        }

        int type = 1; //1 创角  2 有效创角   3 注册人数  4 充值人数

        if(jsonObject.containsKey("type")){
            type = jsonObject.getIntValue("type");
        }

        List<Long> serverIdList = StringUtils.stringToLongList(jsonObject.getString("serverList"), ",");

        AdminResult2 result2 = AdminResult2.defaultInstance();
        for (Long sid : serverIdList) {
            ServerInfo serverInfo = ServerListMgr.getServerInfo(sid);
            if(serverInfo == null){
                continue;
            }

            String serverData = "";
            JSONObject dataObj;
            try {
                serverData = HttpHelper.doPostJsonTimeOut(serverInfo.getWebServerUrl() + "/queryServerRoleCreate", jsonObject.toJSONString(), "UTF-8", new HashMap<>());
                JSONObject jsonObj = JSONObject.parseObject(serverData);
                if(null != jsonObj) {
                    dataObj = jsonObj.getJSONObject("" + serverInfo.getServerId());
                    if (null == dataObj) {
                        if(jsonObj.containsKey("state")){
                            logger.error("state code : {}", jsonObj.get("state"));
                            //直接返回缓存数据
                            dataObj = new JSONObject();
                            if(type == 1){
                                dataObj.put("role", RoleCreateCountMgr.getRoleCreateCountByServerId(serverInfo.getServerId()));
                            }else if(type == 2){
                                dataObj.put("role", RoleCreateCountMgr.getValidCreateCountByServerId(serverInfo.getServerId()));
                            }else if(type == 3){
                                dataObj.put("role", RegisterPlayerNumMgr.getRegisterNumByServerId(serverInfo.getServerId()));
                            }
                            dataObj.put("limit", serverInfo.getCreateRoleCountLimit());
                        }
                    }

                    if(dataObj != null) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("serverId", sid);
                        map.put("num", dataObj.get("role"));
                        result2.getData().add(map);
                    }
                }
            } catch (Exception ex) {
                logger.error("json parse error,{},error:", serverData, ex);
            }
        }
        return result2.toJsonString();
    }


    /**
     *  47.8  修改有效创角接口（直接修改level，不管当前分流规则是否是有效创角）
     */
    @ResponseBody
    @RequestMapping(value = "consoleServerRoleLevel", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String consoleServerRoleLevel(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("channelId") || !jsonObject.containsKey("level")){
            return AdminResult2.failCode(1, "参数不足").toJsonString();
        }

        int channelId = jsonObject.getIntValue("channelId");
        int level = jsonObject.getIntValue("level");

        String areaSplitFlow = "";
        ServerAutoOpenConfig config = AutoOpenServerMgr.getAutoOpenConfigMap().get(channelId);
        if(config != null){
            areaSplitFlow = config.getAreaSplitFlow();
        }
        if(config == null){
            return AdminResult2.failCode(-1, "ServerAutoOpenConfig 缺失").toJsonString();
        }

        ServerAutoOpenConfig serverAutoOpenConfig = AutoOpenServerMgr.initServerAutoOpenConfig(channelId, config.getType(), level, areaSplitFlow);
        new ServerAutoOpenConfigDaoImpl().updateData(serverAutoOpenConfig);
        AutoOpenServerMgr.setAutoOpenConfig(channelId, serverAutoOpenConfig);

        JSONObject paramObj = new JSONObject();
        paramObj.put("channelId", channelId);
        //保持现有的分流规则type
        paramObj.put("type", config.getType());
        paramObj.put("level", level);
        paramObj.put("areaSplitFlow", areaSplitFlow);

        List<ServerInfo> serverList = ServerListMgr.getSplitFlowServerList();
        AdminResult2 result2 = AdminResult2.defaultInstance();

        for (ServerInfo serverInfo : serverList) {
            if(serverInfo.getChannelId() != channelId){
                continue;
            }
            long serverId = serverInfo.getServerId();
            String serverData = "";
            try {
                serverData = HttpHelper.doPostJsonTimeOut(serverInfo.getWebServerUrl() + "/serverRoleType", paramObj.toJSONString(), "UTF-8", new HashMap<>());
                JSONObject jsonObj = JSONObject.parseObject(serverData);
                if(null != jsonObj && jsonObj.containsKey("code")) {

                }else {
                    logger.error("server {} set fail", serverId);
                    result2.getData().add(serverId);
                }
            } catch (Exception ex) {
                logger.error("json parse error,{},error:", serverData, ex);
            }
        }

        //刷新导量服+新服
        List<ServerInfo> openServerList = ServerListMgr.getOpenServerList(channelId);
        for (ServerInfo serverInfo : openServerList) {
            if(!serverInfo.isOpen()){
                serverList.add(serverInfo);
            }
        }

        String msg = CenterReloadHelper.serverMgrReload(serverList, "UserIdMgr", 30);
        result2.setMsg(msg);
        return result2.toJsonString();
    }


    /**
     *  47.9  修改有效创角接口
     */
    @ResponseBody
    @RequestMapping(value = "consoleServerRoleTypeNew", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String consoleServerRoleTypeNew(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("channelId") || !jsonObject.containsKey("type")){
            return AdminResult2.failCode(1, "参数不足").toJsonString();
        }

        int channelId = jsonObject.getIntValue("channelId");
        int type = jsonObject.getIntValue("type");

        int areaType = 1;
        if(jsonObject.containsKey("areaType")){
            areaType = jsonObject.getIntValue("areaType");
        }
        String areaSplitFlow = "";

        ServerAutoOpenConfig config = AutoOpenServerMgr.getAutoOpenConfigMap().get(channelId);

        if(config == null){
            return AdminResult2.failCode(-1, "ServerAutoOpenConfig 缺失").toJsonString();
        }

        if(jsonObject.containsKey("areaSplitFlow")){
            areaSplitFlow = jsonObject.getString("areaSplitFlow");
        }else {
            areaSplitFlow = config.getAreaSplitFlow();
        }

        ServerAutoOpenConfig serverAutoOpenConfig = AutoOpenServerMgr.initServerAutoOpenConfig(channelId, type, config.getLevel(), areaSplitFlow);
        new ServerAutoOpenConfigDaoImpl().updateData(serverAutoOpenConfig);
        AutoOpenServerMgr.setAutoOpenConfig(channelId, serverAutoOpenConfig);

        JSONObject paramObj = new JSONObject();
        paramObj.put("channelId", channelId);
        paramObj.put("type", type);
        paramObj.put("level", config.getLevel());
        paramObj.put("areaSplitFlow", areaSplitFlow);

        List<ServerInfo> serverList = ServerListMgr.getSplitFlowServerList();
        AdminResult2 result2 = AdminResult2.defaultInstance();

        for (ServerInfo serverInfo : serverList) {
            if(serverInfo.getChannelId() != channelId){
                continue;
            }
            long serverId = serverInfo.getServerId();
            String serverData = "";
            try {
                serverData = HttpHelper.doPostJsonTimeOut(serverInfo.getWebServerUrl() + "/serverRoleType", paramObj.toJSONString(), "UTF-8", new HashMap<>());
                JSONObject jsonObj = JSONObject.parseObject(serverData);
                if(null != jsonObj && jsonObj.containsKey("code")) {

                }else {
                    logger.error("server {} set fail", serverId);
                    result2.getData().add(serverId);
                }
            } catch (Exception ex) {
                logger.error("json parse error,{},error:", serverData, ex);
            }
        }

        return AdminResult.defaultInstance().toJsonString();
    }
}
